import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NzMessageService, UploadChangeParam, UploadFile } from 'ng-zorro-antd';
import { FetchService } from '../../../../core/net/fetch.service';

@Component({
    selector: 'app-sf-conference',
    templateUrl: './sf-conference.component.html',
    styleUrls: ['../sf-prod-mng.component.scss']
})
export class SfConferenceComponent implements OnInit {
    searchForm: FormGroup;
    tableData: Array<any> = [];
    pageNum = 1;
    pageSize = 10;
    total: number;
    loading = false;
    form: FormGroup;
    modalTitle: string = '';
    modalShow: boolean = false;

    fileList: UploadFile[] = [];
    uploadUrl = `${(window as any).environment.apiBaseUrl}comm/file/upload`;
    uploadFileId = '';
    fileUploadDisabled = false;
    queryType: "";

    constructor(private fb: FormBuilder,
                private message: NzMessageService,
                private fetchService: FetchService) {
        this.searchForm = this.fb.group({
            rangePickerTime: [[]],
            keywords: [null]
        });
        this.form = this.fb.group({
            id: [null],
            code: [null, Validators.required],
            name: [null, Validators.required],
            meetingUser: [null, Validators.required],
            user: [null, Validators.required],
            meetingTime: [null, Validators.required],
            meetingPlace: [null, Validators.required],
            minutes: [null, Validators.required],
            remark: [null, Validators.required]
        });
    }

    ngOnInit(): void {
        this.queryInfo();
    }

    queryInfo(reset: boolean = false): void {
        if (reset) {
            this.pageNum = 1;
        }
        this.loading = true;
        const params = {
            stTime: this.searchForm.value.rangePickerTime[0],
            edTime: this.searchForm.value.rangePickerTime[1],
            name: this.searchForm.value.keywords,
            pageSize: this.pageSize,
            pageNum: this.pageNum
        };
        this.fetchService.post('safeProduct/wrsSafeProductMeeting/list', params).subscribe(res => {
            this.tableData = res['list'];
            this.total = res['total'];
            this.loading = false;
        });
    }

    openEditModal(isEditable: boolean = true, item?): void {
        this.modalTitle = isEditable ? (item ? `编辑` : '新增') : '详情';
        this.queryType = isEditable ? "" : null;

        this.fileUploadDisabled = !isEditable;
        if (!!item) {
            this.fetchService.get(`safeProduct/wrsSafeProductMeeting/${item.id}`).subscribe(resp => {
                this.form.patchValue(resp);
                if (resp['fileList']) {
                    this.fileList = resp['fileList'].map(file => {
                        return {
                            uid: file.id,
                            name: file.fileName,
                            url: `${(window as any).environment.apiBaseUrl}comm/file/view/${file.id}`,
                            status: 'done',
                            type: file.contentType
                        };
                    });
                }
            });
        } else {
            this.form.patchValue({});
        }
        if (isEditable) {
            this.form.enable();
        } else {
            this.form.disable();
        }
        this.modalShow = true;
    }

    onDelete(id) {
        this.fetchService.get(`safeProduct/wrsSafeProductMeeting/remove/${id}`).subscribe(resp => {
            this.message.info('删除成功');
            this.queryInfo();
        });
    }

    handleChange({file, fileList}: UploadChangeParam): void {
        const status = file.status;
        if (status !== 'uploading') {
            console.log(file, fileList);
        }
        if (status === 'done') {
            this.message.success(`${file.name} 文件上传成功`);
            this.fileList = fileList;
        } else if (status === 'error') {
            this.message.success(`${file.name} 文件上传失败，请重试`);
        }
    }

    onConfirm() {
        if (!this.form.valid) {
            this.message.warning('信息填写有误');
            return;
        }
        const data = {
            ...this.form.value,
            ...{
                fileIds: this.fileList.map(file => {
                    if (file['response']) {
                        return file.response.data.id;
                    } else {
                        return file.uid;
                    }
                }).join(',')
            }
        };
        const url = data.id ? 'safeProduct/wrsSafeProductMeeting/edit' : 'safeProduct/wrsSafeProductMeeting/add';
        this.fetchService.post(url, data).subscribe(res => {
            this.message.success('提交成功');
            this.modalShow = false;
            this.queryInfo();
            this.form.reset();
        });
    }

    onCancel() {
        this.fileList = [];
        this.form.reset();
        this.modalShow = false;
    }
}
